import { IUser } from "./interface";
import * as service from "@/service";
import { Notify, Dialog } from "vant";
import router from "@/router";
import { setCookie } from "@/utils";
interface IResult {
  msg: string;
  status: number;
  token?: string;
  userId?: string;
}
const user: IUser = {
  namespaced: true,
  actions: {
    async getLogin({ commit }, { values }) {
      // todo 1 发请求
      const result: any = await service.fetchLogin(values);
      const name = values.username;
      const username = name.slice(0, 3) + "****" + name.slice(-4);
      switch (result.status) {
        case 0:
          Notify({ type: "danger", message: result.msg });
          break;
        case 1:
          Notify({ type: "success", message: result.msg });
          // 将result信息存入cookie
          setCookie("token", result.token, 7);
          setCookie("userId", result.userId, 7);
          setCookie("username", username, 7);
          router.push({ name: "home" });
          break;

        case 2:
          Notify({ type: "warning", message: result.msg });
          Dialog.alert({
            message: "是否前往注册？",
            theme: "round-button",
            showCancelButton: true,
          })
            .then(() => {
              // on close
              router.push("/register");
            })
            .catch((err) => {
              console.log(err);
            });

          break;

        default:
          break;
      }
      // todo 2 发action
      commit({
        type: "GET_LOGIN",
      });
    },
    async getRegister({ commit }, { values }) {
      // todo 1 发请求
      const result: any = await service.fetchRegister(values);
      switch (result.status) {
        case 0:
          Notify({ type: "danger", message: result.msg });
          break;
        case 1:
          Notify({ type: "success", message: result.msg });
          router.push("/login");
          break;
        default:
          break;
      }
      // todo 2 发action
      commit({
        type: "GET_REGISTER",
      });
    },
  },
};
export default user;
